package privater

import (
	"context"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gtimer"
	"time"
)

func Upgrade(r *ghttp.Request) {
	socket, err := r.WebSocket()
	if err != nil {
		glog.Error(err)
		r.Exit()
	}
	InitConnection(r.GetString("token", "1"), socket)
}

//连接完成初始化工作体
func InitConnection(unique string, conn *ghttp.WebSocket) {
	if set := WebsocketManager.Contains(unique); set {
		old := WebsocketManager.Get(unique).(*Connection)
		old.Close()
	}
	ctx, cancel := context.WithCancel(context.Background())
	client := &Connection{
		Socket:    conn,
		closed:    false,
		writeCh:   make(chan []byte),
		Ctx:       ctx,
		CtxClose:  cancel,
		Unique:    unique,
		Heartbeat: nil,
	}
	client.Heartbeat = Heartbeat(client)
	WebsocketManager.Set(unique, client)
	//开启一个协程做连接读
	go client.read()
	go client.write()
}

func Heartbeat(client *Connection) *gtimer.Entry {
	return gtimer.AddSingleton(time.Second*5, func() {
		client.WriteMsg([]byte("websocket.PingMessage"))
	})
}
